package org.bonorsoft.modules.control.util;

import net.sf.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {

//    private final String getTokenUrl = "http://10.0.0.28:8081/archives?user=";

    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("content-type", "text/html;charset=UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
//            in = new BufferedReader(new InputStreamReader(
//                    connection.getInputStream()));
            in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;

            while ((line = in.readLine()) != null) {
                result += line;

            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * get方式的http请求
     *
     * @param httpUrl 请求地址
     * @return 返回结果
     */
    public static String doGet(String httpUrl) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流，并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }


    public static String post(String token) throws Exception {
        StringBuffer temp = null;
        String ticket = "";
        if (token.length() > 40) {
            ticket = token;
        }
        String strURL = "https://oapi.dingtalk.com/sns/get_persistent_code?access_token=" + token + "&code";
        ticket = "https://oapi.dingtalk.com/gettoken?access_token=" + token + "";
        //		HttpPost httpPost3 = new HttpPost(strURL);
        JSONObject jsonObj = new JSONObject();
//        JSONObject jsonObject3_1 = new JSONObject();
//        //jsonObject3_1.put("tmp_auth_code", code);
//        HttpEntity httpEntity3 = null;
//        httpEntity3 = new StringEntity(jsonObject3_1.toString(),"UTF-8");
//        httpPost3.setEntity(httpEntity3);
        //String strURL = "https://oapi.dingtalk.com/sns/get_persistent_code?access_token="+token+"&code";
        try {
            //System.out.println(strURL);
            URL url = new URL(ticket);// 创建url资源
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 建立http连接
            conn.setDoOutput(true);// 设置允许输出
            conn.setDoInput(true);// 设置允许输入
            conn.setUseCaches(false);// 设置不用缓存
            conn.setRequestMethod("POST");// 设置传参方式
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();// 开始连接请求
            OutputStream out = conn.getOutputStream();
            out.write((jsonObj.toString()).getBytes());// 写入请求的字符串
            out.flush();
            out.close();
            if (conn.getResponseCode() == 200) {// 请求返回的状态
                // 请求返回的数据
                InputStream in = conn.getInputStream();
                try {
                    BufferedReader rd = new BufferedReader(new InputStreamReader(in, "UTF-8"));//这里可以用这个也可以直接用流，buffer的话就是多了个缓存功能
                    int c = 0;
                    temp = new StringBuffer();//请求接口获取json拼接字符串的话，比较长的返回结果String接收是不够的
                    while ((c = rd.read()) != -1) {//这里可以用read也可用readLine，不清楚的话可以查一下两者区别
                        temp.append((char) c);
                    }
                    JSONObject jsonobject = JSONObject.fromObject(temp.toString());
                    //JSONArray dkobject = JSONArray.fromObject(jsonobject.get("recordresult"));//这里就是将json转成对象或者集合
                    //List<Object> list = (List<Object>) JSONArray.toCollection(dkobject,Object.class);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else {
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送POST请求出现异常！" + e);
        }

        return temp.toString();
    }
}
